<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               v-model:page="page"
               v-model:search="search"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @sort-change="sortChange"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               :summary-method="summaryMethod"
               @on-load="onLoad">
      <template #menu-left>
        <el-button
            type="warning"
            icon="el-icon-download"
            @click="handleExport"
        >导出
        </el-button>
        <el-button
            type="success"
            icon="el-icon-sold-out"
            @click="handleSoldOuts"
        >下架
        </el-button>
      </template>

      <template #activeDate-search="{ disabled, size }">
        <el-date-picker
            size="default"
            style="width:94%"
            v-model="this.activeDateRange"
            type="daterange"
            :format="dateFormat"
            :value-format="dateFormat"
            unlink-panels
            start-placeholder="Start Date"
            end-placeholder="End Date"
            clearable
            placeholder="生效日期"
            @change="handleDatePickerChange"
            :picker-options="pickerOptions"
        >
        </el-date-picker>
      </template>

      <template #salesPrice-search="{ disabled, size }">
        <number-range
            v-model="priceRange"
            v-model:min-value="search.priceStart"
            v-model:max-value="search.priceEnd"
            precision="3"
            :valueRange="[0, 99999999]">
        </number-range>
      </template>

      <template #menu="{ row, size, type }">
        <el-tooltip content="下架" placement="top">
          <el-button
              icon="sold-out"
              link
              :size="size"
              :type="type"
              @click="() => handleSoldOut(row.id)"
          >
          </el-button>
        </el-tooltip>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {soldOut, getDetail, add, update, remove, putawayDetails} from "@/api/anwise/customer/customer_material";
import {mapGetters} from "vuex";
import { getToken } from '@/utils/auth';
import { exportBlob } from '@/api/common';
import { downloadXls } from '@/utils/util';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

export default {
  data() {
    return {
      form: {},
      query: {},
      search:{},
      stockDateRange:[],
      deliDateRange:[],
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      pickerOptions: {},
      selectionList: [],
      activeDateRange:[],
      priceRange: [],
      dateFormat:"YYYY-MM-DD",
      option: {
        selection:true,
        rowKey:'id',
        height:'auto',
        calcHeight: 30,
        tip: false,
        searchShow: false,
        searchMenuSpan: 6,
        border: true,
        index: true,
        reserveSelection:true,
        labelWidth: 150,
        indexWidth:100,
        menuWidth: 80,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        stripe: true,
        searchIndex: 3,
        searchIcon: false,
        searchLabelWidth:120,
        searchEnter:true,
        menu:true,
        showSummary: true,
        column: [
          {
            label: "物料名称",
            prop: "materialName",
            type: "input",
            search: true,
            overHidden: true,
            sortable: true,
            width:130
          },
          {
            label: "客户条码",
            prop: "barCode",
            type: "input",
            search: true,
            overHidden: true,
            sortable: true,
            width:130
          },
          {
            label: "物料编号",
            prop: "materialNo",
            type: "input",
            search: true,
            overHidden: true,
            sortable: true,
            width:130
          },
          {
            label: "品牌",
            prop: "programName",
            type:"select",
            filterable:true,
            dicUrl: '/api/blade-anwise/customer_group/select',
            props: {
              label: 'programName',
              value: 'programName',
            },
            dataType: 'string',
            rules: [{
              required: false,
              message: "请选择品牌",
              trigger: "blur"
            }],
            search: true,
            overHidden: true,
            sortable: true,
            width:120,
          },
          {
            label: "品牌分组",
            prop: "programGroup",
            type: "select",
            dicUrl: "/blade-system/dict-biz/dictionary?code=program_group",
            filterable: true,
            props: {
              label: 'dictValue',
              value: 'dictValue',
            },
            dataType: 'string',
            rules: [{
              required: false,
              message: "请选择品牌分组",
              trigger: "blur"
            }],
            search: true,
            overHidden: true,
            sortable: true,
            width:130
          },
          {
            label: "客户编号",
            prop: "customerNo",
            type: "input",
            search: true,
            overHidden: true,
            sortable: true,
            width:130
          },
          {
            label: "客户名称",
            prop: "customerName",
            type: "input",
            search: true,
            overHidden: true,
            sortable: true,
            width:130
          },
          {
            label: "贸易条款",
            prop: "tradeTerms",
            type: 'select',
            filterable:true,
            dicUrl: '/api/blade-system/dict-biz/dictionary?code=trade_terms',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            dataType: 'string',
            search: true,
            overHidden: true,
            sortable: true,
            width:130
          },
          {
            label: "币别",
            prop: "rmb",
            search: true,
            type: "select",
            filterable: true,
            overHidden: true,
            sortable: true,
            width:130,
            dicUrl: '/api/blade-system/dict-biz/dictionary?code=rmb',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            dataType: 'string',
          },
          {
            label: "单价",
            prop: "salesPrice",
            type: "number",
            search: true,
            overHidden: true,
            sortable: true,
            width:130
          },
          {
            label: "生效日期",
            prop: "activeDate",
            type: "date",
            format: "YYYY年MM月DD日",
            valueFormat: "YYYY-MM-DD",
            search: true,
            overHidden: true,
            sortable: true,
            width:130,
            rules: [{
              required: true,
              message: "请选择生效日期",
              trigger: "blur"
            }],
          },
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["userInfo","permission"]),
    permissionList() {
      return {
        viewBtn: this.validData(this.permission.stock_in_details_view, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    handleSoldOuts(){
      this.$confirm('是否确定下架?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(this.ids)
        soldOut(this.ids).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "下架成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // });
      });
    },
    handleSoldOut(id){
      this.$confirm('是否确定下架?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      soldOut(id).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "下架成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // });
      });
    },
    handleExport(){
      NProgress.start();
      exportBlob(
          `/blade-anwise/material/customer_material/exportDetails?${this.website.tokenHeader
          }=${getToken()}`, this.query
      ).then(res => {
        downloadXls(res.data, `上架明细${this.$dayjs().format('YYYYMMDDHHmmss')}.xlsx`);
        NProgress.done();
      });
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
    },
    summaryMethod ({ columns, data }) {
      const sums = [];
      if (columns.length > 0) {
        sums[1] = '合计：';
        columns.forEach((column, index) => {
          let prop = column.property
          if (['salesPrice'].includes(prop)) {
            let values = data.map(item => Number(item[prop] || 0));
            let all = values.length !== 0 ? sums[index] = values.reduce((a, b) => {
              return a + b;
            }) : 0
            sums[index] = this.$toFixed(all,3)
            // if (prop == 'salesPrice') {
            //   sums[index] = this.$toFixed(all,0)
            // }
          }
        });
      }
      return sums;
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.priceRange = [];
      this.search.priceStart = '';
      this.search.priceEnd = '';
      this.activeDateRange = [];
      this.search.activeDateStart = '';
      this.search.activeDateEnd = '';
      this.onLoad(this.page);
    },
    sortChange(val) {
      console.log(val)
      this.sort = {
        prop: val.prop,
        order: val.order
      };
      let order = "";
      if (this.sort.prop && this.sort.order) {
        if (this.sort.order === "descending") {
          order = `${this.sort.prop} desc`
        } else {
          order = `${this.sort.prop} asc`
        }
      }
      this.query.orderBy = order;
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      // Object.assign(this.query, params)
      this.page.currentPage = 1
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage){
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize){
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      putawayDetails(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleDatePickerChange(value) {
      console.log(value);
      if (value) {
        this.search.activeDateStart = value[0];
        this.search.activeDateEnd = value[1];
      } else {
        this.search.activeDateStart = '';
        this.search.activeDateEnd = '';
      }
    },
  }
};
</script>

<style>
</style>
